//
//  MYComposeViewController.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/22.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class MYComposeViewController: UIViewController {
    
    //按钮的监听事件
    @objc private func selectPicture() {
        print("选择图片")
        //更新约束
        pictureSelectorController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
    }
    @objc private func selectEmoticon() {
        print("选择表情")
    }

    @objc private func close() {
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
    //print("send")
        guard let token = MYUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            SVProgressHUD.showErrorWithStatus("暂未登录")
            return
        }
        HMNetworkTools.sharedTools.sendStatus(token, status: textView.text,imageList: pictureSelectorController.imageList ) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布失败")
            return
            }
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //发送成功后返回首页
            self.close()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        //注册键盘弹出和收起的通知
        registerNotification()
    }
    
    @objc private func keyboardWillChange(n: NSNotification) {
        let userInfo = n.userInfo!
        let rect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //自动布局的页面动画效果
        let offsetY = -ScreenHeight + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    //MARK: 注册通知
    private func registerNotification() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    private func setupUI() {
        setNavBar()
        setTextView()
        setToolBar()
        setPictureSelector()
        
        //将toolBar移到最顶层
        view.bringSubviewToFront(toolBar)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        textView.resignFirstResponder()
    }
    
    private lazy var rightBarButtonItem: UIBarButtonItem = {
        let btn = UIButton()
        //设置文案
        btn.setTitle("发送", forState: .Normal)
       //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        //添加点击事件
        btn.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        let barButtonItem = UIBarButtonItem(customView: btn)
        return barButtonItem
    }()
    
    
    private lazy var textView: UITextView = {
    
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.backgroundColor = UIColor(white: 0.95, alpha: 1)
        tv.delegate = self
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        return tv
    }()
    
    //占位文本
    private lazy var placeHolderLabel: UILabel = UILabel(text: "想飞上天和太阳肩并肩~~", textColor: UIColor.lightGrayColor(), fontSize: 18)
    
    //底部工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //选择图片控制器
    private lazy var pictureSelectorController: MYPictureSelectorController = MYPictureSelectorController()
    
    //移除通知
    deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

//MARK: 设置UI界面
extension MYComposeViewController {
    
    private func setPictureSelector() {
    
        //1.添加子视图控制器  
        //以后如果要是使用控制器的视图之前一定要提前持有该控制器
        self.addChildViewController(pictureSelectorController)
        //2.根视图 添加视图控制器的视图
        view.addSubview(pictureSelectorController.view)
        
        //设置约束
        pictureSelectorController.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            //设置初始高度
            make.height.equalTo(0)
        }
        
    }
    
    private func setToolBar() {
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
        }
        
        var items = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background","actionName": "selectPicture"]]

        //添加UIBarButtonItem到数组中
        for item in itemSettings {
            if let actionName = item["actionName"] {
        let barButtonItem = UIBarButtonItem(imageName: item["imageName"],  target: self, action: Selector(actionName))
                items.append(barButtonItem)
        }
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //移除最后一个
        items.removeLast()
        toolBar.items = items
        
    }
    
    private func setTextView() {
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    

    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = rightBarButtonItem
        //设置右边按钮不可交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置导航条自定义视图
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        navigationItem.titleView = myView
        let titleLabel = UILabel(text: "发布微博", textColor: UIColor.darkGrayColor(), fontSize: 16)
        let nameLabel = UILabel(text: MYUserAccountViewModel.sharedAccountViewModel.userAccount?.name ?? "", textColor: UIColor.lightGrayColor(), fontSize: 13)
        //添加
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myView.snp_top)
            make.centerX.equalTo(myView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
        }
        
    }
    
}


extension MYComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        //隐藏占位文本
        placeHolderLabel.hidden = textView.hasText()
        //发送按钮可交互
        navigationItem.rightBarButtonItem?.enabled = true
    }
    
}




